<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use app\common\model\Category as CategoryModel;
use app\admin\model\LitestoreGoods;
use app\admin\model\Recovery;
use app\admin\model\Address;
use app\admin\model\Repair;
use app\common\model\Car as CarModel;
use app\common\model\Order;
use addons\epay\library\Service as EpayService;
use EasyWeChat\Foundation\Application as WXPAY_APP;
use EasyWeChat\Payment\Order as WXPAY_ORDER;
use think\Config;
use addons\third\model\Third;

/**
 * 购物车接口
 */
class Car extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->user_id = $this->auth->id;
        // $this->user_id = 2;
    }  
    /**
     * 购物车页面进到确认订单页 car_json的值[{"car_id":23,"num":5},{"car_id":22,"num":2}]
     * @ApiSummary  (获取默认收货地址以及已选的手机属性参数。"")
     * @ApirMethod   (POST)
     * @ApiRoute    (/api/car/to_sure)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="car_json",type=json,required=true,description="")
     * @ApiReturnParams (name="address", type="string", required=true, description="地址信息，没有就返回空值")
     */
    public function to_sure()
    {
        $to_array = json_decode(htmlspecialchars_decode(input('car_json')),true);
       // halt($to_array);

        $return = [];
        $return['totalprice'] = 0;
        foreach ($to_array as $key => $value) {
            $shopping_data = Db::name('shoppingcar')->where(['id'=>$value['car_id']])->find();
            $shopping_data['car_id'] = $value['car_id'];
            $return['goods_list'][] = $shopping_data;
            $return['totalprice'] += $value['num']*$shopping_data['unit_price'];
        }
        $address = Db::name('address')->where(['user_id'=>$this->user_id,'isdefault'=>1])->find();
        $return['address'] = $address?$address:'';
        
        $this->success('确认订单数据',$return);
    }
    
     /**
     * 购物车商品下单,同时调起支付 car_json的值[{"car_id":23,"num":5},{"car_id":22,"num":2}]
     * @ApiSummary  ()
     * @ApirMethod   (POST)
     * @ApiRoute    (/api/car/meanwhile)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="car_json",type=json,required=true,description="")
     * @ApiParams   (name="address_id",type=id,required=true,description="收货地址id")
     */
    public function meanwhile()
    {
        $Order = new Order;
        $address_id = input('address_id');
        if(empty($address_id))$this->error('收货地址为空');
        $car_json = htmlspecialchars_decode(input('car_json'));

        $to_array = json_decode($car_json,true);
        if(count($to_array)>1){
            $return = $up_car_data = [];
            $return['total_price'] = $return['num'] = 0;
            foreach ($to_array as $key => $value) {
                $nowshoppingcar = CarModel::get($value['car_id']);

                $spec_data = Db::name('litestore_goods_spec')->where('goods_spec_id',$nowshoppingcar['goods_spec_id'])->find();
                if(empty($spec_data))$this->error($nowshoppingcar['goods_name'].'的'.$nowshoppingcar['goods_attr'].'数据被后台修改了，请重新加入购物车');
                // halt($spec_data);
                // halt($value['num']);
                if($value['num']>$spec_data['stock_num']){
                    $this->error($nowshoppingcar['goods_name'].'的'.$nowshoppingcar['goods_attr'].'库存不足');
                }

                $goods_id_array[$key]['goods_id'] = $nowshoppingcar['goods_id'];//用于订单模型里面减库存
                $goods_id_array[$key]['goods_spec_id'] = $nowshoppingcar['goods_spec_id'];//用于订单模型里面减库存
                $goods_id_array[$key]['num'] = $value['num'];//用于订单模型里面减库存

                $shoppingcar_id[] = $value['car_id'];//购物车json数据保存到订单表中

                $up_car_data[$key]['id'] = $value['car_id'];
                $up_car_data[$key]['num'] = $value['num'];
                $up_car_data[$key]['total_price'] = $value['num']*$nowshoppingcar['unit_price'];
                $up_car_data[$key]['status'] = 0;

                $return['total_price'] += $value['num']*$nowshoppingcar['unit_price'];
                $return['num'] += $value['num'];
            }
            $return['address_id'] = $address_id;

            $return['spec_type'] = 30;
            $return['shoppingcar_id'] = json_encode($shoppingcar_id);//购物车json数据保存到订单表中
            $order_detail = $Order->order_add_together($this->user_id,$return,$goods_id_array);

            // halt($up_car_data);
            // 修改购物车的数量用于关联商品跟订单,修改该status数据为0
            $CarModel = new CarModel;
            $CarModel->saveAll($up_car_data);
        //单件商品时候
        }else{
            foreach ($to_array as $key => $value) {
                $nowshoppingcar = CarModel::get($value['car_id']);

                $up_car_data['id'] = $value['car_id'];
                $up_car_data['total_price'] = $value['num']*$nowshoppingcar['unit_price'];
                $up_car_data['status'] = 0;
                $up_car_data['num'] = $value['num'];

                $params['address_id'] = $address_id;
                $params['num'] = $value['num'];
                $params['goods_spec_id'] = $nowshoppingcar['goods_spec_id'];
                $params['goods_id'] = $nowshoppingcar['goods_id'];
                $params['spec_type'] = $nowshoppingcar['spec_type'];
                $params['rent_date'] = $nowshoppingcar['rent_date'];
                $order_detail = $Order->order_add($this->user_id, $params);
            }
            $CarModel = new CarModel;
            $CarModel->isUpdate(true)->save($up_car_data);
            
        }
        // halt($order_detail);
        if($order_detail){
            // 发起微信支付
            $this->init_wx_pay_for_wxapp();
         
            $third = Third::where(['user_id' => $this->user_id, 'platform' => 'wxapp'])->find();
        
            $payment = $this->wxapp->payment;
            $attributes = [
                'trade_type'       => 'JSAPI',
                'body'             => Config::get('site.name'),
                'detail'           => Config::get('site.name'),
                'out_trade_no'     => $order_detail['order_no'],
                'openid'           => $third['openid'],
                'total_fee'        => $order_detail['total_price']*100,
                'notify_url'       => Config::get('site.cdnurl').'api/order/callback_for_wxapp',
            ];
            $order_pay = new WXPAY_ORDER($attributes);
            $result = $payment->prepare($order_pay);
            if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
                $prepayId = $result->prepay_id;
                $config = $payment->configForJSSDKPayment($prepayId); // 返回数组
                return $this->success('订单创建成功,预支付成功',$config);
            }
            return $this->error('微信支付调用失败',$result);
        }else if($order_detail==2){
            $this->error('当前库存不足');
        }
        
    }

    private function init_wx_pay_for_wxapp(){
        $config = get_addon_config('epay');
        $options = [
            'debug'  => true,
            'log' => [
                'level' => 'debug',
                'file'  => LOG_PATH . '/tmp/easywechat.log',
            ],
            'app_id'   => $config['wechat']['miniapp_id'],// 小程序 APPID
            'secret'   => $config['wechat']['app_secret'],//小程序密钥
            'payment' => [
                'merchant_id'        =>  $config['wechat']['mch_id'],//小程序商户号
                'key'                =>  $config['wechat']['key'],//小程序支付密钥
                'notify_url'         =>  \think\Request::instance()->domain().'/api/order/callback_for_wxapp',
            ],

        ];
        $this->wxapp = new WXPAY_APP($options);
    }

    /**
     * 加入购物车
     * @ApirMethod   (POST)
     * @ApiRoute    (/api/car/insert_shopcart)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="goods_id",type=int,required=true,description="上传手机id")
     * @ApiParams   (name="num",type=int,required=true,description="商品数量")
     * @ApiParams   (name="rent_date",type=int,required=false,description="租期时间选择")
     * @ApiParams   (name="total_price",type=decimal,required=false,description="总价格")
     * @ApiParams   (name="goods_spec_id",type=int,required=true,description="无论是单规格还是多规格该值是唯一的。，单规格情况下goods_spec_id在spec里面。多规格情况下goods_spec_id，在spec_list里面")
     * @ApiParams   (name="spec_type",type=int,required=true,description="商品类型:10=单规格,20=多规格")
     */
    public function insert_shopcart()
    {
        $return = input();
        $goods_id = input('goods_id');
        if(empty($goods_id))$this->error('请上传手机id:goods_id');
        if(empty($this->user_id))$this->error('请重新登录');

        $exist_data = Db::name('shoppingcar')->where(['user_id'=>$this->user_id,'goods_id'=>$goods_id,'status'=>1])->find();
        if($exist_data)$this->error('已经加入过购物车了，请前往购物车查看');

        $return['goods_attr']='';

        $goods_data = Db::name('litestore_goods')->where(['goods_id'=>$return['goods_id']])->find();

        $spec_data = Db::name('litestore_goods_spec')->where(
          [
            'goods_spec_id'=>$return['goods_spec_id'],
            'goods_id'=>$return['goods_id']
          ]
          )->find();

        if(empty($spec_data))$this->error('抱歉，商品规格不存在');
        // 单规格情况下
        if($return['spec_type']==10){
            // 如果选择了租机
            if(!empty($return['rent_date'])){
                // 根据 goods_spec_id 找到 租期价格数据

                $return['goods_attr'] = $return['rent_date']; 
                $return['rent'] = $return['rent_date']; 

                $return['unit_price'] = $spec_data['day_price'];

            }else{
                //正常单规格买
                $return['unit_price'] = $spec_data['goods_price'];//单价
            }

            // 单规格的照片
            $return['cover'] = $goods_data['cover'];

        }else{
            //多规格的情况下

            // 查询选择了的属性值
            $spec_sku_id_array = explode('_', $spec_data['spec_sku_id']);
            foreach ($spec_sku_id_array as $key => $value) {
                $return['goods_attr'] .= Db::name('litestore_spec_value')->where(['id'=>$value])->value('spec_value').'+';
            }
            // 如果选择了租机
            if(!empty($return['rent_date'])){
                // 根据 goods_spec_id 找到 租期价格数据
                $return['rent'] = $return['rent_date']; 
                $return['goods_attr'] .= $return['rent_date']; 
                $return['unit_price'] = $spec_data['day_price'];

            }else{
                //正常多规格买
                $return['unit_price'] = $spec_data['goods_price'];//单价
            }
            $return['cover'] = $spec_data['spec_image'];
        }
        $return['goods_attr'] = rtrim($return['goods_attr'],'+');

        $return['goods_name'] = $goods_data['goods_name'];
        $return['createtime'] = time();
        $return['updatetime'] = time();
        $return['user_id'] = $this->user_id;
        unset($return['rent_date']);
        $res = Db::name('shoppingcar')->insert($return);$this->success('加入购物车成功');
    }
    
    /**
     * 我的购物车列表
     */
    public function my_shoppingcar(){
      $data = Db::name('shoppingcar')->where(['user_id'=>$this->user_id,'status'=>1])->field("*,id as car_id,FROM_UNIXTIME(updatetime,'%Y-%m-%d %H:%i:%s') as updatetime")->order('updatetime desc')->select();
      $this->success('我的购物车列表',$data);
    }
    
    /**
     * 清空购物车
     * @param int $id 多个id用逗号隔开
     */
    public function clear_shoppingcar(){

      $id_array = explode(',', input('id'));
      $res = Db::name('shoppingcar')->where('id','in',$id_array)->where(['user_id'=>$this->user_id,'status'=>1])->delete();
      if($res)$this->success('操作成功');
      $this->error('操作失败');
    }

  

  

}
